package com.aio.news.home.adapter;

import java.util.ArrayList;
import java.util.List;

import com.aidi.lib.TAInjectView;
import com.aio.news.AioApplication;
import com.aio.news.BaseFragment;
import com.aio.news.R;
import com.aio.news.home.fragment.NewsDetailFragment;
import com.aio.news.model.NewsModel.NewsItem;
import com.aio.news.utils.StringUtil;
import com.squareup.picasso.Picasso;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LatestAdapter extends BaseAdapter {

	private BaseFragment mFragment;
	private List<NewsItem> mItems = new ArrayList<NewsItem>();

	public LatestAdapter(BaseFragment mFragment) {
		this.mFragment = mFragment;
	}

	public void addItems(List<NewsItem> items) {
		this.mItems.addAll(items);
		notifyDataSetChanged();
	}

	public void refresh() {
		this.mItems.clear();
	}

	@Override
	public int getCount() {
		return mItems.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final NewsItem mItem = mItems.get(position);
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = View.inflate(mFragment.getActivity(),
					R.layout.latest_adapter_layout, null);
			AioApplication.getInjector().injectView(convertView, holder);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if (!TextUtils.isEmpty(mItem.url)) {
			holder.img.setVisibility(View.VISIBLE);
			Picasso.with(mFragment.getActivity()).load(mItem.url)
					.into(holder.img);
		} else {
			holder.img.setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(mItem.title)) {
			holder.title.setText(mItem.title);
		} else {
			holder.title.setText("");
		}
		if (!TextUtils.isEmpty(mItem.comed)) {
			holder.author.setText(mItem.comed);
		} else {
			holder.author.setText("");
		}
		if (mItem.time > 0) {
			holder.date.setText(StringUtil.getDateToStringLong(mItem.time));
		}
		convertView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle b = new Bundle();
				b.putString("id", mItem.id);
				mFragment.startFullFragment(NewsDetailFragment.class, b);
			}
		});
		return convertView;
	}

	class ViewHolder {
		@TAInjectView(id = R.id.img)
		ImageView img;
		@TAInjectView(id = R.id.title)
		TextView title;
		@TAInjectView(id = R.id.date)
		TextView date;
		@TAInjectView(id = R.id.author)
		TextView author;
	}

}
